package com.lb.sssq.actions;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.edais.domain.IpLogBean;
import com.edais.domain.OrderFormRecharge;
import com.edais.domain.PayDataBean;
import com.edais.domain.RetBean;
import com.edais.domain.UserAccountDetail;
import com.edais.domain.WeixinMediaBinding;
import com.edais.log.IpLog;
import com.edais.service.CaptchaService;
import com.edais.service.CenterService;
import com.edais.service.SMSService;
import com.edais.service.UserCardService;
import com.edais.service.UserService;
import com.edais.service.WeixinBindingService;
import com.edais.util.Consts;
import com.edais.util.JsonUtil;
import com.edais.util.LianlianPayUtil;
import com.edais.util.weixinAbout.SendWeiXinUtil;
import com.edais.util.youdun.UdRequestUtil;
import com.edais.util.zsht.ZSHTPayThridPartyFunctionUtil;
import com.google.gson.JsonObject;
import com.lb.sssq.domain.PaymentInfo;
import com.lb.sssq.util.CommonUtil;
import com.lb.sssq.util.LLPayHostingEnvUtil;
import com.lb.sssq.util.Md5Algorithm;
import com.lb.sssq.util.Message;
import com.lb.sssq.util.RSAUtil;

@Controller
@RequestMapping("/sssqPay")

public class SssqPayAction  implements Serializable{
	private static final Log logger = LogFactory.getLog(SssqPayAction.class);

	@Autowired
	private CenterService centerService;

	@Autowired
	private UserService userService;

	@Autowired
	private UserCardService userCardService;

	@Autowired
	private SMSService sMSService;
	
	@Autowired
	private WeixinBindingService weixinBindingService;
	
	@Autowired
	private CaptchaService captchaService;

	/**
	 * 查询银行卡信息接口
	 * @param request
	 * @param response
	 */
	
	@RequestMapping(value = "/queryBankCard")
	public void queryBankCard(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 用户id
		String userId = paramsMap.get("userId");
		String cardNo = paramsMap.get("cardNo");
		
		if (StringUtils.isBlank(cardNo)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/queryBankCard 传入银行卡号为空");
			return;
		}
		
		if (StringUtils.isBlank(userId)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/queryBankCard 传入用户ID为空");
			return;
		}
		
		// 获取用户账户详情
		try {
			UserAccountDetail userAccountDetail = userService.getUserAccountDetail(userId);
			
			// 判断用户是否使命认证
			if (!"1".equals(userAccountDetail.getIs_create_acct())
					|| !"Y".equals(userAccountDetail.getIdcard_validate())) {
				String result = CommonUtil.setResultStringCn(
						resultMap, Consts.ERROR_CODE,
						Consts.ErrorMsg.MSG00001,
						"当前登录用户还没有进行实名认证，请实名认证之后再进行充值！");
				CommonUtil.responseJson(result, response);
				return;
			}
			
			Map<String, String> reqJavaMap = new LinkedHashMap<String, String>();
			reqJavaMap.put("userId", userId);
			reqJavaMap.put("cardNo", cardNo);
			reqJavaMap.put("payType", "D");

			// 查询卡银行卡bin信息是否存在
			Map<String, String> userCardBinMap = queryCardBinLLPay(request, response, reqJavaMap);
			String rescode = userCardBinMap.get("rescode").toString();
			if (!(rescode.equals("00"))) {
				String result = CommonUtil.setResultStringCn(
						resultMap, Consts.ERROR_CODE,
						Consts.ErrorMsg.MSG00001,
						"输入的银行卡卡号不正确，未能查询到银行卡信息，请重新输入！");
				CommonUtil.responseJson(result, response);
				return;
			}else {
				// 输入的银行卡是信用卡时，提示信息
				if ("3".equals(userCardBinMap.get("cardType"))) {
					String result = CommonUtil.setResultStringCn(
							resultMap, Consts.ERROR_CODE,
							Consts.ErrorMsg.MSG00001,
							"对不起，暂不支持信用卡，请使用本人借记卡支付！");
					CommonUtil.responseJson(result, response);
					return;
				}
			}
			
			String bankCode = "";
			Map<String,Object> bankParamsMap = new HashMap<String,Object>();
			bankCode = userCardBinMap.get("bankCode");
			bankParamsMap.put("bankCode", bankCode);
			Map<String,Object> bankResMap = this.userCardService.queryBankIdByBankCode(bankParamsMap);
			String bankExist = bankResMap.get("isExist").toString();
			if(!Boolean.parseBoolean(bankExist)){
				String result = CommonUtil.setResultStringCn(
						resultMap, Consts.ERROR_CODE,
						Consts.ErrorMsg.MSG00001,
						"对不起，暂不支持此银行，请选择其他银行卡支付！");
				CommonUtil.responseJson(result, response);
				return;
			}
			
			resultMap.put("bankCode", bankCode);
			resultMap.put("bankName", userCardBinMap.get("bankName"));
			
			String payPlatformId = bankResMap.get("payPlatformId").toString();
			//判断是掌上汇通还是连连支付
			
			if(payPlatformId.equals("2")){
				resultMap.put("topUpFlag", "ZSHTPAY");
			}else{
				resultMap.put("topUpFlag", "LLPAY");
			}
			
			String result = CommonUtil.setResultStringCn(resultMap,
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			CommonUtil.responseJson(result, response);
			
		} catch (Exception e) {
			logger.error("sssqPay/queryBankCard 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					"","查询用户银行卡相关信息！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	/**
	 * 快捷支付_获取支付数据
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getReqContentForLianlian")
	public void getReqContentForLianlian(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 用户id
		String userId = paramsMap.get("userId");
		String appFlag = paramsMap.get("appFlag");
		// ip记录
		String ip = CommonUtil.getClientIP(request);

		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("银行卡充值");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);
		logBean.setDetail(userId+"在APP端进行了充值预下单操作");

		try {
			// 参数检查
			paramsMap.put("buyFlag", "N");//代表购买
			Map<String, String> checkRes = checkRechargeParam(paramsMap);
			
			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
				logger.error("充值_获取支付参数数据检查失败" + checkRes.get("message"));
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						resultMap, checkRes.get("code"),
						"", checkRes.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}

			// 获取用户账户详情
			UserAccountDetail userAccountDetail = userService.getUserAccountDetail(userId);

			
			Map<String, String> reqJavaMap = new LinkedHashMap<String, String>();
			reqJavaMap.put("userId", userId);
			reqJavaMap.put("cardNo", paramsMap.get("backCardId"));
			reqJavaMap.put("payType", "D");

			// 查询卡银行卡bin信息是否存在
			Map<String, String> userCardBinMap = queryCardBinLLPay(request, response, reqJavaMap);
			String rescode = userCardBinMap.get("rescode").toString();
			if (!(rescode.equals("00"))) {
				String result = CommonUtil.setResultStringCn(
						resultMap, Consts.ERROR_CODE,
						Consts.ErrorMsg.MSG00001,
						"输入的银行卡卡号不正确，未能查询到银行卡信息，请重新输入！");
				CommonUtil.responseJson(result, response);
				return;
			} else {
				// 输入的银行卡是信用卡时，提示信息
				if ("3".equals(userCardBinMap.get("cardType"))) {
					String result = CommonUtil.setResultStringCn(
							resultMap, Consts.ERROR_CODE,
							Consts.ErrorMsg.MSG00001,
							"对不起，暂不支持信用卡，请使用本人借记卡支付！");
					CommonUtil.responseJson(result, response);
					return;
				}
			}
			String bankCode = "";
			Map<String,Object> bankParamsMap = new HashMap<String,Object>();
			bankCode = userCardBinMap.get("bankCode");
			bankParamsMap.put("bankCode", bankCode);
			Map<String,Object> bankResMap = this.userCardService.queryBankIdByBankCode(bankParamsMap);
			String bankExist = bankResMap.get("isExist").toString();
			if(!Boolean.parseBoolean(bankExist)){
				String result = CommonUtil.setResultStringCn(
						resultMap, Consts.ERROR_CODE,
						Consts.ErrorMsg.MSG00001,
						"对不起，暂不支持此银行，请选择其他银行卡支付！");
				CommonUtil.responseJson(result, response);
				return;
			}
			
			List<String> notExsitBankList = new ArrayList<String>();
			notExsitBankList.add("04135810");
			notExsitBankList.add("04012900");
			/*notExsitBankList.add("04031000");*/
			
			if(notExsitBankList.contains(bankCode)){
				String result = CommonUtil.setResultStringCn(
						resultMap, Consts.ERROR_CODE,
						Consts.ErrorMsg.MSG00001,
						"对不起，暂不支持此银行，请选择其他银行卡支付！");
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 拼接提交连连支付的参数
			PaymentInfo payInfo = new PaymentInfo();
			// 商户编号
			payInfo.setOid_partner(LLPayHostingEnvUtil.getValue("oid_partner"));
			// 签名方式
			payInfo.setSign_type(LLPayHostingEnvUtil.getValue("sign_type"));
			
			// 商户业务类型
			payInfo.setBusi_partner(LLPayHostingEnvUtil.getValue("busi_partner_virtual"));
			// 生成订单号
			String noOrder = createNoOrder("LBMB");
			// 商户唯一订单号
			payInfo.setNo_order(noOrder);
			// 商户订单时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String dtOrder = sdf.format(new Date());
			payInfo.setDt_order(dtOrder);
			// 商品名称
			payInfo.setName_goods("联璧支付购买充值");
			// 订单描述
			payInfo.setInfo_order("联璧充值");
			// 充值金额
			payInfo.setMoney_order(paramsMap.get("rechargeAmount"));
			// 服务器异步通知地址
			payInfo.setNotify_url(LLPayHostingEnvUtil.getValue("notify_url"));
			
			/**
			 *  风控控制参数
			 */
			JsonObject riskObject = new JsonObject();
			// 商品类目  (P2P小额贷款 :2009)
			riskObject.addProperty("frms_ware_category", "2009");
			// 商户用户唯一标识 
			riskObject.addProperty("user_info_mercht_userno", paramsMap.get("userId"));
			// 注册时间
			riskObject.addProperty("user_info_dt_register", userAccountDetail.getReg_time());
			// 用户注册姓名
			riskObject.addProperty("user_info_full_name", userAccountDetail.getReal_name());
			// 用户注册证件号码
			riskObject.addProperty("user_info_id_no", userAccountDetail.getId_card());
			// 是否实名认证
			riskObject.addProperty("user_info_identify_state", "1");
			// 实名认证方式
			riskObject.addProperty("user_info_identify_type", "3");
			//用户注册证件类型
			riskObject.addProperty("user_info_id_type", "0");
			// 绑定手机号
			riskObject.addProperty("user_info_bind_phone", userAccountDetail.getMobile());
			payInfo.setRisk_item(riskObject.toString());
			
			// 用户ID
			// 如果是迁移用户则传入迁移用户ID
			if ("90".equals(userAccountDetail.getUtm_source())) {
				payInfo.setUser_id(userAccountDetail.getDeposit_dock_userid());
			} else {
				payInfo.setUser_id(userId);
			}
			// 证件类型 0:身份证
			payInfo.setId_type("0");
			// 证件号码
			payInfo.setId_no(userAccountDetail.getId_card());
			// 账号名称
			payInfo.setAcct_name(userAccountDetail.getReal_name());
			// 银行卡号
			payInfo.setCard_no(paramsMap.get("backCardId"));

			// 加签名
			String sign_src = getSignStr(payInfo);
			if (sign_src.startsWith("&")) {
				sign_src = sign_src.substring(1);
			}
			String sign = "";
			if ("RSA".equals(request.getParameter("sign_type"))) {
				sign = RSAUtil.sign(LLPayHostingEnvUtil.getValue("trader_pri_key"), sign_src);
			} else {
				sign_src += "&key=" + LLPayHostingEnvUtil.getValue("md5_key");
				try {
					sign = Md5Algorithm.getInstance().md5Digest(sign_src.getBytes("utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			payInfo.setSign(sign);

			String llpayNoAgree = request.getParameter("llpayNoAgree");
			// 签约协议号
			if (StringUtils.isNotBlank(llpayNoAgree)) {
				payInfo.setNo_agree(llpayNoAgree);
			}
			reqJavaMap.put("cardPhone", userAccountDetail.getMobile());
			// 判断用户是否已绑定卡 如果未绑定卡 则保存银行卡信息
			if (StringUtils.isBlank(userAccountDetail.getCard_number())) {
				// 保存银行卡信息
				reqJavaMap.put("bankCode", userCardBinMap.get("bankCode").toString());
				reqJavaMap.put("bankName", userCardBinMap.get("bankName").toString());
				reqJavaMap.put("bindindReqNum", noOrder);
				reqJavaMap.put("acctName",userAccountDetail.getReal_name());
				reqJavaMap.put("idCard", userAccountDetail.getId_card());
				
				logger.info("===========保存银行卡信息：==reqJavaMap:"+reqJavaMap.toString());
				Map<String, String> relMap = saveUserBankCardInfo(request, response, reqJavaMap);
				
				// 保存银行卡失败时
				if (!relMap.get("rescode").equals(Consts.SUCCESS_CODE)) {
					String result = CommonUtil.setResultStringCn(
							resultMap, Consts.ERROR_CODE,
							Consts.ErrorMsg.MSG00001,
							"银行卡信息保存失败！");
					CommonUtil.responseJson(result, response);
					return;
				}
				
//				/************ 调用有盾开始【充值绑卡】**************/
//				try {
//					Map<String, String> udParam = new HashMap<String, String>();
//					udParam.put("device_id", paramsMap.get("device_id")); // 设备号
//					udParam.put("trace_id", paramsMap.get("trace_id")); // 设备跟踪ID
//					udParam.put("user_id", userAccountDetail.getId().toString()); // 账户ID
//					udParam.put("user_ip_address", ip); // 用户请求IP
//					String from = paramsMap.get("from");
//					if("LBIOS".equals(from)){
//						from = "IOS";
//					}else if("LBAndroid".equals(from)){
//						from = "Android";
//					}else if("".equals(from)){
//						from = "PC";
//					}
//					udParam.put("platform", from); // 平台 Android IOS PC
//					udParam.put("mobile", userAccountDetail.getMobile()); // 手机号
//					udParam.put("id_number", userAccountDetail.getId_card()); // 身份证号
//					UdRequestUtil.sendUd("/ud/bindCard", udParam);
//				} catch (Exception e) {
//					logger.error("**************充值绑卡调用【有盾】异常！");
//					e.printStackTrace();
//				}
//				/************ 调用有盾结束【充值绑卡】**************/
				
			} else {
				reqJavaMap.put("bindindReqNum", noOrder);

				Map<String, Object> updateBindCardMap = updateUserBindindBankCardInfo(request, response, reqJavaMap);
				
				if (!Consts.SUCCESS_CODE.equals(updateBindCardMap.get("rescode"))) {
					String result = CommonUtil.setResultStringCn(
							resultMap, Consts.ERROR_CODE,
							Consts.ErrorMsg.MSG00001,
							"银行卡信息更新失败！");
					CommonUtil.responseJson(result, response);
					return;
				}
			}
			if (StringUtils.isNotBlank(ip)) {
				logBean.setStatus(Consts.SUCCESS_CN);
				IpLog.printIpLog(logBean);
			}
			
			Map<String, String> dealMap = new HashMap<String, String>();
			// 保存订单信息
			String signSrc =  JSON.toJSONString(payInfo).replaceAll("=","||");
			dealMap.put("userId", userId);
			dealMap.put("moneyOrder", paramsMap.get("rechargeAmount"));
			dealMap.put("signSrc", signSrc);
			dealMap.put("noOrder", noOrder);
			dealMap.put("oidPartner",LLPayHostingEnvUtil.getValue("oid_partner"));
			dealMap.put("dtOrder", dtOrder);
			dealMap.put("rechargeChannel", "MOBILE");
			dealMap.put("cardNumber", paramsMap.get("backCardId"));
			dealMap.put("platform", "LIANLIANPAY");
			Map<String, Object> dealResultMap = dealLLPayFastPayToken(request, response, dealMap);
			
			if (!Consts.SUCCESS_CODE.equals(dealResultMap.get("rescode"))) {
				logger.info("============充值前保存订单失败："+dealResultMap.toString()+"=====");
				String result = CommonUtil.setResultStringCn(
						resultMap, Consts.ERROR_CODE,
						Consts.ErrorMsg.MSG00001,
						"充值前保存订单信息失败！");
				CommonUtil.responseJson(result, response);
				return;
			}

			resultMap.put("msg", "success");
			resultMap.put("payInfo", JSON.toJSONString(payInfo));

			logger.info("=============getReqContentForLianlian返回的参数：["+resultMap.toString()+"]====");
			String result = CommonUtil.setResultStringCn(resultMap,
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.error("sssqPay/getReqContentForLianlian 异常:" + e.getMessage());
			if (StringUtils.isNotBlank(ip)) {
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					"","获取连连支付参数异常！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	/**
	 * 获取支付数据参数检查
	 * @return
	 * @throws Exception
	 */
	private Map<String,String> checkRechargeParam(Map<String, String> map) throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		
		// 用户id
		String userId = map.get("userId");
		// 绑定银行卡id
		String backCardId = map.get("backCardId");
		// 充值金额(元)
		String cardAmountStr = map.get("rechargeAmount");
		
		// 程序必须参数未传入
		if (StringUtils.isBlank(userId)
				|| StringUtils.isBlank(backCardId)) {
			result.put("code", Consts.ERROR_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return result;
		}

		// 充值金额未输入
		if (StringUtils.isBlank(cardAmountStr)) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_IS_LESSTHAN_1YUAN);
			return result;
		}

		// 充值金额检查（必须是1元以上）
		boolean flag = cardAmountStr.matches("^[0-9]*[\\.]{0,1}[0-9]{0,2}$");
		if (!flag) {
			// 输入的值为非法字符
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.MOUNT_IS_NON_STANDARD);
			return result;
		}

		result.put("code", Consts.SUCCESS_CODE);
		result.put("message", Consts.SUCCESS_DESCRIBE);
		return result;
	}
	
	/**
	 * 预支付订单信息
	 * 
	 * @param request
	 * @param response
	 */
	private Map<String, Object> dealLLPayFastPayToken(HttpServletRequest request,
			HttpServletResponse response, Map<String, String> requestMap) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 请求参数
		String userId = requestMap.get("userId");
		String moneyOrder = requestMap.get("moneyOrder");
		String signSrc = requestMap.get("signSrc");
		
		String noOrder = requestMap.get("noOrder");
		String oidPartner = requestMap.get("oidPartner");
		String dtOrder = requestMap.get("dtOrder");
		//充值渠道
		String rechargeChannel = requestMap.get("rechargeChannel");
		//银行卡卡号
		String cardNumber = requestMap.get("cardNumber");
		//渠道
		String platform = requestMap.get("platform");
		
		// 非空判断
		if (StringUtils.isBlank(userId)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "userId不能为空！");
			logger.debug("===================传入userId为空");
			return jsonMap;
		}
		
		if (StringUtils.isBlank(rechargeChannel)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "rechargeChannel不能为空！");
			logger.debug("===================传入rechargeChannel为空");
			return jsonMap;
		}

		if (StringUtils.isBlank(moneyOrder)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "moneyOrder不能为空！");
			logger.debug("===================传入moneyOrder为空");
			return jsonMap;
		}

		if (StringUtils.isBlank(signSrc)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "signSrc不能为空！");
			logger.debug("===================传入signSrc为空");
			return jsonMap;
		}

		if (StringUtils.isBlank(noOrder)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "noOrder不能为空！");
			logger.debug("===================传入noOrder为空");
		}
		if (StringUtils.isBlank(oidPartner)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "oidPartner不能为空！");
			logger.debug("===================传入oidPartner为空");
		}
		if (StringUtils.isBlank(dtOrder)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "dtOrder不能为空！");
			logger.debug("===================传入dtOrder为空");
		}
		if (StringUtils.isBlank(cardNumber)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "cardNumber不能为空！");
			logger.debug("===================传入cardNumber为空");
		}
		

		try {
			Map<String, Object> paramsMap = new HashMap<String, Object>();
			paramsMap.put("userId", userId);
			paramsMap.put("moneyOrder", moneyOrder);
			paramsMap.put("signSrc", signSrc);
			paramsMap.put("noOrder", noOrder);
			paramsMap.put("oidPartner", oidPartner);
			paramsMap.put("dtOrder", dtOrder);
			paramsMap.put("rechargeChannel", rechargeChannel);
			paramsMap.put("cardNumber", cardNumber);
			paramsMap.put("platform", platform);
			
			jsonMap = this.userCardService.dealLLPayFastPayToken(paramsMap);

			return jsonMap;
		} catch (Exception e) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			logger.error("dealLLPayFastPayToken 异常:" + e.getCause());
			return jsonMap;
		}
	}
	
	
	/**
	 * 连连支付回调(仅充值)
	 * 
	 * @param request
	 * @return response
	 */
	@RequestMapping(value = "/receiveRecNotify")
	public void receiveNotify(PrintWriter printWriter, HttpServletRequest request, HttpServletResponse response) 
			throws UnsupportedEncodingException {
		logger.info("====================SssqPayAction.receiveNotify方法开始执行：充值成功 进入回调方法====================");
		// 连连回调通知
		RetBean retBean = new RetBean();
		retBean.setRet_code("9999");
		retBean.setRet_msg("交易失败");
		
		String reqStr = LianlianPayUtil.readReqStr(request);
		if (!StringUtils.isBlank(reqStr)) {
			logger.debug("接收支付异步通知数据：【" + reqStr + "】");
			try {
				if (!LianlianPayUtil.checkSign(reqStr,
						LLPayHostingEnvUtil.getValue("yt_pub_key"),
						LLPayHostingEnvUtil.getValue("md5_key"))) {
					retBean.setRet_code("9999");
					retBean.setRet_msg("交易失败");
					logger.info("====支付异步通知验签失败!");
				}
			} catch (Exception e) {
				logger.debug("异步通知报文解析异常：" + e);
				retBean.setRet_code("9999");
				retBean.setRet_msg("交易失败");
			}
			
			// 解析异步通知对象
			PayDataBean payDataBean = JSON.parseObject(reqStr,PayDataBean.class);
			if(payDataBean == null){
				logger.error("连连支付交易结果转换bean对象出错!");
				return;
			}
			
			String tradeState = payDataBean.getResult_pay();// 获取交易结果
			logger.debug(">>>>>>>>>连连支付交易结果通知--支付结果: " + tradeState);
			logger.debug(">>>>>>>>>连连支付交易结果通知--通知数据: " + reqStr);
			
			String ip = CommonUtil.getClientIP(request);
			
			// 只有交易成功才能执行充值动作
			if ("SUCCESS".equals(tradeState)) {
				
				// 根据商户唯一订单号查询用户银行卡信息
				Map<String, String> reqJavaMap = new LinkedHashMap<String, String>();
				reqJavaMap.put("bindingReqNum", payDataBean.getNo_order());
				reqJavaMap.put("noAgree", payDataBean.getNo_agree()==null?"":payDataBean.getNo_agree());
				reqJavaMap.put("moneyOrder", payDataBean.getMoney_order());
				reqJavaMap.put("oidPayBill", payDataBean.getOid_paybill());
				reqJavaMap.put("reqStr", reqStr.replace("=", "||"));

				Map<String, Object> resltMap = updateUserBankCardByReqNum(request, response, reqJavaMap);
				if(Consts.SUCCESS_CODE.equals(resltMap.get("rescode"))){
					String userId = String.valueOf(resltMap.get("userId")==null?"":resltMap.get("userId"));
					String moneyOrder = payDataBean.getMoney_order();
					retBean.setRet_code("0000");
					retBean.setRet_msg("交易成功");
					//推送购买微信/短信接口
					try {
						sendMeidaAndSMS(userId,moneyOrder);
						//发送个推消息----add by gongyanlan
						String smsNo="sms01001";//充值,config_sms表中参数,
						String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
						String[] smsParams={moneyOrder,"",""};
						Map<String,Object> map=new HashMap<String,Object>();
						map.put("userId", userId);
						map.put("mobile", mobile);
						map.put("title", "充值成功通知");//标题
						map.put("messageDetailTypeNew", "3");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
						map.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
						map.put("smsParams", smsParams);//消息模板里需要替换的变量
						map.put("smsNo", smsNo);
						sMSService.sendGetuiMSG(map);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						logger.info("[***************************充值推送微信/短信失败]");
					}
				}else if("99998".equals(resltMap.get("rescode"))){
					retBean.setRet_code("0000");
					retBean.setRet_msg("交易成功");
				}else{
					retBean.setRet_code("9999");
					retBean.setRet_msg("交易失败");
				}
			}
		} else {
			retBean.setRet_code("9999");
			retBean.setRet_msg("交易失败");
			logger.info("====支付异步通知验签失败!");
		}
		
		String req_data = JSON.toJSONString(retBean);
		req_data = new String(req_data.toString().getBytes("utf-8"), "iso8859-1");
		printWriter.write(req_data);
		printWriter.flush();
		printWriter.close();
	}
	
	/**
	 * 随机生成订单
	 * 
	 * @return
	 */
	public String createNoOrder(String title) {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String currTime = outFormat.format(now);

		String strReq = currTime;
		Random random = new Random();
		String result = "";
		for (int i = 0; i < 8; i++) {
			result += random.nextInt(10);
		}

		String requestNo = title + strReq + result;
		return requestNo;
	}

	
	/**
	 * 连连支付-根据用户银行卡查询银行卡卡bin信息
	 * 
	 * @param request
	 * @param response
	 */
	private Map<String, String> queryCardBinLLPay(HttpServletRequest request,
			HttpServletResponse response, Map<String, String> requestMap) {
		Map<String, String> jsonMap = new HashMap<String, String>();

		String cardNo = requestMap.get("cardNo");// 银行卡卡号
		String payType = requestMap.get("payType");// 支付类型

		if (StringUtils.isBlank(cardNo)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "银行卡卡号不能为空！");
			return jsonMap;
		}

		try {
			return userCardService.queryCardBinLL(requestMap);
		} catch (Exception e) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return jsonMap;
		}
	}
	
	/**
	 * 保存银行卡信息
	 * 
	 * @param request
	 * @param response
	 */
	private Map<String, String> saveUserBankCardInfo(HttpServletRequest request,
			HttpServletResponse response, Map<String, String> requestMap) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		String userId = requestMap.get("userId");
		String cardNo = requestMap.get("cardNo");
		String bankCode = requestMap.get("bankCode");
		String bankName = requestMap.get("bankName");
		String bindindReqNum = requestMap.get("bindindReqNum");
		String acctName = requestMap.get("acctName");
		String idCard = requestMap.get("idCard");

		// 非空判断
		if (StringUtils.isBlank(userId)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "用户ID不能为空！");
			logger.info("========userId is null!!!====");
			return jsonMap;
		}

		if (StringUtils.isBlank(cardNo)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "cardNo不能为空！");
			logger.info("========cardNo is null!!!====");
			return jsonMap;
		}

		if (StringUtils.isBlank(bankCode)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "bankCode不能为空！");
			logger.info("========bankCode is null!!!====");
			return jsonMap;
		}
		if (StringUtils.isBlank(bankName)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入银行卡名称不能为空！");
			logger.info("========bankName is null!!!====");
			return jsonMap;
		}
		if (StringUtils.isBlank(bindindReqNum)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入请求号不能为空！");
			logger.info("========bindindReqNum is null!!!====");
			return jsonMap;
		}
		if (StringUtils.isBlank(acctName)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入用户真实姓名不能为空！");
			logger.info("========acctName is null!!!====");
			return jsonMap;
		}
		if (StringUtils.isBlank(idCard)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入身份证不能为空！");
			logger.info("========idCard is null!!!====");
			return jsonMap;
		}

		try {
			return userCardService.saveUserBankCardInfo(requestMap);
		} catch (Exception e) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return jsonMap;
		}
	}
	
	/**
	 * 连连支付前更新银行卡信息
	 */
	private Map<String, Object> updateUserBindindBankCardInfo(HttpServletRequest request,
			HttpServletResponse response, Map<String, String> requestMap) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		String userId = requestMap.get("userId");
		String cardNumber = requestMap.get("cardNo");
		String bindingReqNum = requestMap.get("bindindReqNum");
		String cardPhone = requestMap.get("cardPhone");
		// 非空判断
		if (StringUtils.isBlank(userId)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入userId不能为空！");
			return jsonMap;
		}

		if (StringUtils.isBlank(cardNumber)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入cardNumber不能为空！");
			return jsonMap;
		}
		if (StringUtils.isBlank(bindingReqNum)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入bindingReqNum不能为空！");
			return jsonMap;
		}

		try {
			Map<String, Object> paramsMap = new HashMap<String, Object>();
			paramsMap.put("userId", userId);
			paramsMap.put("cardNumber", cardNumber);
			paramsMap.put("bindingReqNum", bindingReqNum);
			paramsMap.put("cardPhone", cardPhone);
			jsonMap = this.userCardService
					.updateUserBindindBankCardInfo(paramsMap);
			return jsonMap;
		} catch (Exception e) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return jsonMap;
		}
	}
	
	/**
	 * 连连支付后更新用户信息
	 * 
	 * @param request
	 * @param response
	 */
	private Map<String, Object> updateUserBankCardByReqNum(HttpServletRequest request,
			HttpServletResponse response, Map<String, String> paramsMap) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		String bindingReqNum = paramsMap.get("bindingReqNum");// 用户id
		String noAgree = paramsMap.get("noAgree");
		String moneyOrder = paramsMap.get("moneyOrder");
		String oidPayBill = paramsMap.get("oidPayBill");
		String reqStr = paramsMap.get("reqStr");

		if (StringUtils.isBlank(bindingReqNum)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入bindingReqNum不能为空！");
			logger.debug("=======bindingReqNum 不能为空！==");
			return jsonMap;
		}
		if (StringUtils.isBlank(noAgree)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入noAgree不能为空！");
			logger.debug("=======noAgree 不能为空！==");
			return jsonMap;
		}
		if (StringUtils.isBlank(moneyOrder)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入moneyOrder不能为空！");
			logger.debug("=======moneyOrder 不能为空！==");
			return jsonMap;
		}
		if (StringUtils.isBlank(oidPayBill)) {
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", "传入oidPayBill不能为空！");
			logger.debug("=======oidPayBill 不能为空！==");
			return jsonMap;
		}
		try {
			Map<String, Object> requestMap = new HashMap<String, Object>();
			requestMap.put("bindingReqNum", bindingReqNum);
			requestMap.put("noAgree", noAgree);
			requestMap.put("moneyOrder", moneyOrder);
			requestMap.put("oidPayBill", oidPayBill);
			requestMap.put("reqStr", reqStr);
			
			
			jsonMap= this.userCardService.coreLLPayNotify(requestMap);
			
			return jsonMap;
		} catch (Exception e) {
			logger.error("==queryBankCardByBindingReqNum 异常:" + e.getCause());
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return jsonMap;
		}
	}
	
	/**
	 * 拼接支付签名
	 * 
	 * @param payInfo
	 * @return
	 */
	public String getSignStr(PaymentInfo payInfo) {
		StringBuffer strBuf = new StringBuffer();

		strBuf.append("busi_partner=");
		strBuf.append(payInfo.getBusi_partner());
		strBuf.append("&dt_order=");
		strBuf.append(payInfo.getDt_order());
		strBuf.append("&info_order=");
		strBuf.append(payInfo.getInfo_order());
		strBuf.append("&money_order=");
		strBuf.append(payInfo.getMoney_order());
		strBuf.append("&name_goods=");
		strBuf.append(payInfo.getName_goods());
		strBuf.append("&no_order=");
		strBuf.append(payInfo.getNo_order());
		strBuf.append("&notify_url=");
		strBuf.append(payInfo.getNotify_url());
		strBuf.append("&oid_partner=");
		strBuf.append(payInfo.getOid_partner());
		if (StringUtils.isNotBlank(payInfo.getRisk_item())) {
			strBuf.append("&risk_item=");
			strBuf.append(payInfo.getRisk_item());
		}
		strBuf.append("&sign_type=");
		strBuf.append(payInfo.getSign_type());

		
		return strBuf.toString();
	}
	
	/***
	 * 本地调试地址
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/sendMediaSmsTEST")
	public void sendMediaSmsTEST(HttpServletRequest request, HttpServletResponse response){
		try {
			sendMeidaAndSMS("28644858","10000");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/***
	 * 生产调试地址
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/shengcanSendMediaSmsTEST")
	public void shengcanSendMediaSmsTEST(HttpServletRequest request, HttpServletResponse response){
		try {
			sendMeidaAndSMS("28645244","0.01");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据USERID发送短信/微信
	 * @param userId
	 */
	public void sendMeidaAndSMS(String userId,String moneyOrder) throws Exception{
		//封装用户ID
		WeixinMediaBinding mediaBinding = new WeixinMediaBinding();
		mediaBinding.setUserId(Integer.parseInt(userId));
		
		//先推送微信，微信成功不发短信，失败再发短信
		String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
		String mediaUid = weixinBindingService.queryMediaUid(mediaBinding);//通过用户ID实体类查询微信标识
		
		//TODO 逻辑判断
		if(null == mediaUid || "null".equalsIgnoreCase(mediaUid) || "".equalsIgnoreCase(mediaUid)){
			logger.info("[推送短信息]因手机号："+mobile+"并未绑定微信");
			//活期充值成功，发送短信 by ouyy
			String cpType="";
			String smsNo="sms01001";//config_sms表中参数
			String tsje=moneyOrder;
								
			if (StringUtils.isBlank(userId) 
					|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
				logger.debug("sssqPay/receiveRecNotify sendSMS 传入参数为空");
			}
			try{
				// 发送短信
				if(StringUtils.isEmpty(cpType)){
					sMSService.getSMS(userId,smsNo,tsje);	
				}else{
					sMSService.getSMS(userId,smsNo,tsje,cpType);	
				}
			} catch (Exception e) {
				logger.error("sssqPay/receiveRecNotify sendSMS异常:" + e.getCause());
			}
		}else{
			Map<String,String> weixinTMap = new HashMap<String,String>();
			weixinTMap.put("mediaUid", mediaUid);//微信用户唯一标识 
			weixinTMap.put("money", moneyOrder);//充值金额
			weixinTMap.put("functionScope", "recharge");//接口标识
			
			boolean sendRusult = SendWeiXinUtil.sendWeiXin(weixinTMap);
			if(!sendRusult){
				logger.info("[微信推送失败][推送短信息]因手机号："+mobile+"并未绑定微信或者未关注联币钱包微信号");
				//活期充值成功，发送短信
				String cpType="";
				String smsNo="sms01001";//config_sms表中参数
				String tsje=moneyOrder;
				if (StringUtils.isBlank(userId) 
						|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
					logger.debug("sssqPay/receiveRecNotify sendSMS 传入参数为空");
				}
				try{
					// 发送短信
					if(StringUtils.isEmpty(cpType)){
						sMSService.getSMS(userId,smsNo,tsje);	
					}else{
						sMSService.getSMS(userId,smsNo,tsje,cpType);	
					}
				} catch (Exception e) {
					logger.error("sssqPay/receiveRecNotify sendSMS异常:" + e.getCause());
				}
			}else{
				logger.info("[微信推送]手机号："+mobile+"推送成功");
			}
		}
	}
	//新增掌上汇通支付方法
	
	/**
	 * 掌上汇通支付申请方法
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/zshtTopUp")
	public void zshtTopUp(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		
		String cardNo =  paramsMap.get("cardNo");
		String moneyOrder = paramsMap.get("moneyOrder");
		String userId = paramsMap.get("userId");
		String bankCode = paramsMap.get("bankCode");
		String bankName = paramsMap.get("bankName");
		String phoneNum = paramsMap.get("phoneNum");
		
		//非空校验
		if (StringUtils.isBlank(cardNo)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/zshtTopUp 传入银行卡号为空");
			return;
		}
		
		if (StringUtils.isBlank(userId)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/zshtTopUp 传入用户ID为空");
			return;
		}
		
		if (StringUtils.isBlank(moneyOrder)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/zshtTopUp 传入moneyOrder为空");
			return;
		}
		
		if (StringUtils.isBlank(bankCode)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/zshtTopUp 传入bankCode为空");
			return;
		}
		
		if (StringUtils.isBlank(bankName)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/zshtTopUp 传入bankName为空");
			return;
		}
		
		if (StringUtils.isBlank(phoneNum)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/zshtTopUp 传入phoneNum为空");
			return;
		}
		
		String noOrder = createNoOrder("ZSHTMB");
		try {
			UserAccountDetail userAccountDetail = userService.getUserAccountDetail(userId);
			Map<String, String> reqJavaMap = new LinkedHashMap<String, String>();
			reqJavaMap.put("userId", userId);
			reqJavaMap.put("cardNo", cardNo);
			reqJavaMap.put("cardPhone", phoneNum);
			//判断是否存在银行卡
			if (StringUtils.isBlank(userAccountDetail.getCard_number())) {
				// 保存银行卡信息
				reqJavaMap.put("bankCode", bankCode);
				reqJavaMap.put("bankName", bankName);
				reqJavaMap.put("bindindReqNum", noOrder);
				reqJavaMap.put("acctName",userAccountDetail.getReal_name());
				reqJavaMap.put("idCard", userAccountDetail.getId_card());
				
				logger.info("===========保存银行卡信息：==reqJavaMap:"+reqJavaMap.toString());
				Map<String, String> relMap = saveUserBankCardInfo(request, response, reqJavaMap);
				
				// 保存银行卡失败时
				if (!relMap.get("rescode").equals(Consts.SUCCESS_CODE)) {
					String result = CommonUtil.setResultStringCn(
							resultMap, Consts.ERROR_CODE,
							Consts.ErrorMsg.MSG00001,
							"银行卡信息保存失败！");
					CommonUtil.responseJson(result, response);
					return;
				}
			} else {
				reqJavaMap.put("bindindReqNum", noOrder);

				Map<String, Object> updateBindCardMap = updateUserBindindBankCardInfo(request, response, reqJavaMap);
				
				if (!Consts.SUCCESS_CODE.equals(updateBindCardMap.get("rescode"))) {
					String result = CommonUtil.setResultStringCn(
							resultMap, Consts.ERROR_CODE,
							Consts.ErrorMsg.MSG00001,
							"银行卡信息更新失败！");
					CommonUtil.responseJson(result, response);
					return;
				}
			}
			
			Map<String, String> requestMap = new HashMap<String, String>();
			requestMap.put("userId", userId);
			requestMap.put("moneyOrder", moneyOrder);
			requestMap.put("orderdesc", "联币钱包用户"+userId+"进行支付");
			requestMap.put("bankcard", cardNo);
			requestMap.put("cardusername", userAccountDetail.getReal_name());
			requestMap.put("idno", userAccountDetail.getId_card());
			requestMap.put("cardphone", phoneNum);
			requestMap.put("noOrder", noOrder);
			
			Map<String,String> thridResMap =ZSHTPayThridPartyFunctionUtil.zshtTopUp(requestMap);
			
			if (thridResMap == null
					|| "sysException".equals(thridResMap.get("rescode"))) {
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE,
						thridResMap.get("resmsg_cn"), "支付申请失败失败");
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			} else if ("BusinessException".equals(thridResMap.get("rescode"))) {
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE,
						"", String.valueOf(thridResMap.get("resmsg_cn")));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			String rescode = thridResMap.get("rescode");
			String resmsg = thridResMap.get("resmsg_cn");
			String resJson = thridResMap.get("resJson");
			
			
			if("00".equals(rescode)){
				String orderNo = thridResMap.get("orderNo");
				String paytoken = thridResMap.get("paytoken");
				
				Map<String, String> dealMap = new HashMap<String, String>();
				// 保存订单信息
				dealMap.put("userId", userId);
				dealMap.put("moneyOrder", moneyOrder);
				dealMap.put("signSrc", resJson);
				dealMap.put("noOrder", noOrder);
				dealMap.put("oidPartner",LLPayHostingEnvUtil.getValue("zshtMerId"));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String merOrderDate = sdf.format(new Date());
				dealMap.put("dtOrder", merOrderDate);
				dealMap.put("rechargeChannel", "MOBILE");
				dealMap.put("cardNumber", cardNo);
				dealMap.put("platform", "ZSHTPAY");
				Map<String, Object> dealResultMap = dealLLPayFastPayToken(request, response, dealMap);
				
				if (!Consts.SUCCESS_CODE.equals(dealResultMap.get("rescode"))) {
					logger.info("============充值前保存订单失败："+dealResultMap.toString()+"=====");
					String result = CommonUtil.setResultStringCn(
							resultMap, Consts.ERROR_CODE,
							Consts.ErrorMsg.MSG00001,
							"充值前保存订单信息失败！");
					CommonUtil.responseJson(result, response);
					return;
				}
				
				resultMap.put("rescode", Consts.SUCCESS_CODE);
				resultMap.put("resmsg_cn", "支付申请成功");
				resultMap.put("orderNo", orderNo);
				resultMap.put("paytoken", paytoken);
				
			}else{
				resultMap.put("rescode", Consts.ERROR_CODE);
				resultMap.put("resmsg", "");
				resultMap.put("resmsg_cn", resmsg);
			}
			
			String result = JsonUtil.getJsonStringFromMap(resultMap);
			CommonUtil.responseJson(result, response);
			
		}  catch (Exception e) {
			logger.error("sssqPay/zshtTopUp 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					"","掌上汇通支付错误！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
		
	}
	
	/**
	 * 掌上汇通验证支付
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/checkZshtTopUp")
	public void checkZshtTopUp(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		
		String userId = paramsMap.get("userId");
		String paytoken = paramsMap.get("paytoken");
		String orderNo = paramsMap.get("orderNo");
		String checkCode = paramsMap.get("checkCode");
		
		if (StringUtils.isBlank(userId)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/checkZshtTopUp 传入用户ID为空");
			return;
		}
		
		if (StringUtils.isBlank(paytoken)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/checkZshtTopUp 传入paytoken为空");
			return;
		}
		
		if (StringUtils.isBlank(orderNo)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/checkZshtTopUp 传入orderNo为空");
			return;
		}
		
		if (StringUtils.isBlank(checkCode)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("sssqPay/checkZshtTopUp 传入checkCode为空");
			return;
		}
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("orderNo", orderNo);
		requestMap.put("paytoken", paytoken);
		requestMap.put("checkCode", checkCode);
		
		try{
			
			Map<String,String> thridResMap =ZSHTPayThridPartyFunctionUtil.checkTopUp(requestMap);
			if (thridResMap == null
					|| "sysException".equals(thridResMap.get("rescode"))) {
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE,
						thridResMap.get("resmsg_cn"), "支付申请失败失败");
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			} else if ("BusinessException".equals(thridResMap.get("rescode"))) {
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE,
						"", String.valueOf(thridResMap.get("resmsg_cn")));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			String rescode = thridResMap.get("rescode");
			String resmsg = thridResMap.get("resmsg_cn");
			
			if("00".equals(rescode)){
				resultMap.put("rescode", Consts.SUCCESS_CODE);
				resultMap.put("resmsg_cn", "支付成功");
				resultMap.put("resmsg", "");
			}else{
				resultMap.put("rescode", Consts.ERROR_CODE);
				resultMap.put("resmsg", "");
				resultMap.put("resmsg_cn", resmsg);
			}
			String result = JsonUtil.getJsonStringFromMap(resultMap);
			CommonUtil.responseJson(result, response);
			
		}catch (Exception e) {
			logger.error("sssqPay/checkZshtTopUp 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					"","掌上汇通验证支付错误！");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	
	
	
	
	
}
